#include <json/json.h>
#include <http/HttpServer.h>

class MainApplication : public Application
{
public:
	bool main()
	{
		if (GetCmdParam("--help") || GetCmdParam("?"))
		{
			puts("  parameter list");
			puts("---------------------------");
			puts("  -t : table name");
			puts("  -d : database source");
			puts("  -l : language [cpp|java]");
			puts("---------------------------");
			puts("");

			return 0;
		}

		const char* dbid = GetCmdParam("-d");
		const char* name = GetCmdParam("-t");
		const char* lang = GetCmdParam("-l");
		
		if (name == NULL || *name == 0)
		{
			ColorPrint(eRED, "%s\n", "please input table name use '-t' parameter");
	
			return false;
		}

		HttpRequest request("exportentity");

		request.setParameter("dbid", dbid);
		request.setParameter("name", name);

		sp<HttpResponse> response = HttpServer::Instance()->getLocaleResult(request);

		if (!response)
		{
			ColorPrint(eRED, "%s\n", "export entity failed");

			return false;
		}

		SmartBuffer data = response->getResult();

		if (data.isNull())
		{
			ColorPrint(eRED, "%s\n", "export entity failed");
	
			return false;
		}

		string content = JsonElement(data.str()).asString("content");

		if (content.empty())
		{
			ColorPrint(eRED, "%s\n", "export entity failed");
	
			return false;
		}

		if (lang && strcasecmp(lang, "JAVA") == 0)
		{
			size_t pos = content.rfind(":");

			if (pos == string::npos)
			{
				ColorPrint(eRED, "%s\n", "export entity failed");
		
				return false;
			}

			content = content.substr(pos + 1);
			content = stdx::replace(content, ")", "");
			content = stdx::replace(content, "rint(", "Integer ");
			content = stdx::replace(content, "rdouble(", "Double ");
			content = stdx::replace(content, "rstring(", "String ");

			pos = content.rfind("}");

			if (pos == string::npos)
			{
				ColorPrint(eRED, "%s\n", "export entity failed");
		
				return false;
			}

			content = stdx::format("public class Entity{%s}", content.substr(0, pos).c_str());
		}

		puts(content.c_str());

		return true;
	}
};

START_APP(MainApplication)